package context

import (
	"go-test/src/com/miao/common/set"
	"go-test/src/com/miao/common/utils"
	"log"
	"sync"
)

type Groups struct {
	sync.RWMutex
	groupsmap map[string]*set.Set //set装载类型*channelContext
}

func NewGroups() *Groups {
	return &Groups{ groupsmap:make(map[string]*set.Set)}
}

func (groups *Groups) GetGroupsmap()  map[string]*set.Set{
	return groups.groupsmap
}

func (groups *Groups) bind(chanel *ChannelContext, group string){
	if utils.StrIsEmpty(group) {
		log.Print("group not allow empty")
		return
	}
	groupSet :=groups.groupsmap[group]
	if groupSet==nil {
		groups.groupsmap[group]=set.New()
	}
	groups.groupsmap[group].Add(chanel)
	chanel.Group.Add(group)
}

func (groups *Groups) findId(group string) *ChannelContext {
	return nil
}

func (groups *Groups) findSet(group string) *set.Set {
	if utils.StrIsEmpty(group){
		log.Print("group not allow empty")
		return nil
	}
	return groups.groupsmap[group]
}

func (groups *Groups) unbind(chanel *ChannelContext, group string)  {
	if utils.StrIsEmpty(group){
		log.Print("group not allow empty")
		return
	}
	groups.Lock()
	defer groups.Unlock()
	groupSet:=groups.groupsmap[group]
	if groupSet==nil {
		log.Print(group,"并不存在")
		return
	}
	groupSet.Remove(chanel)
	if groupSet.IsEmpty() {
		delete(groups.groupsmap,group)
	}
	chanelGroupSet :=chanel.Group
	if &chanelGroupSet!=nil {
		chanelGroupSet.Remove(group)
	}
}

func (groups *Groups) unbindAll(chanel *ChannelContext){
	chanelGroupSet :=chanel.Group
	if chanelGroupSet==nil {
		return
	}
	chanel.Lock()
	defer chanel.Unlock()
	list := chanelGroupSet.List()
	for i := range list {
		//解除绑定
		groups.unbind(chanel,list[i].(string))
	}
	chanelGroupSet.Clear()
	chanel.Group=nil
}


